import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/dialog_task.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

GlobalKey<_TaskTabPageState> taskTransferKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskEnterKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskStorageKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskAuctionKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskDestroyKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskSampleKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskChangeKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskReturnKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskDonationKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskMoveKey = GlobalKey();
GlobalKey<_TaskTabPageState> taskOutKey = GlobalKey();

class TaskTabPage extends StatefulWidget {
  final String model;
  final int receiveType;

  TaskTabPage({Key key, this.model, this.receiveType}) : super(key: key);

  @override
  _TaskTabPageState createState() => _TaskTabPageState();
}

class _TaskTabPageState extends State<TaskTabPage>
    with AutomaticKeepAliveClientMixin {
  List list = [];
  int currentPage = 1;
  int lastPage = 1;
  bool loadSuccess = false;
  var eventBus = new EventBus();
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _loadData();
    super.initState();

    eventBus.on("task_enter_check", (parmas) {
      setState(() {
        list.removeAt(parmas['index']);
      });
    });

    eventBus.on("task_auction_out", (parmas) {
      if (mounted) {
        setState(() {
          list.removeAt(parmas['index']);
        });
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    eventBus.off("task_enter_check");
    // eventBus.off("task_auction_out");
  }

  // 切换接收状态
  void changeReceive() {
    Timer.periodic(Duration(milliseconds: 50), (timer) {
      _loadData();
      timer.cancel();
    });
  }

  // 加载数据
  void _loadData({bool loadMore = false}) async {
    loadSuccess = false;

    if (loadMore) {
      currentPage++;
    } else {
      currentPage = 1;
    }

    DioUtils.request("Todolist/getlist",
        context: context,
        method: "POST",
        params: {
          'model': widget.model,
          'type': widget.receiveType,
          'current_page': currentPage,
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            if (loadMore) {
              list.addAll(res["data"]["data"]);
            } else {
              list = res["data"]["data"];
            }
            currentPage = res['data']['current_page'];
            lastPage = res['data']['last_page'];
            loadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 接受任务
  void _receiveTask(int id, int index, Map item) {
    DioUtils.request("enter/receive",
        context: context, method: "POST", params: {'id': id}, onSuccess: (res) {
      if (res['code'] == 1) {
        _showTaskDialog(id);
        setState(() {
          list.removeAt(index);
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 下拉刷新
  void _onRefresh() async {
    _refreshController.loadComplete();
    _loadData();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 加载更多
  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 300));

    if (currentPage == lastPage) {
      _refreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if (currentPage < lastPage) {
      _loadData(loadMore: true);
      _refreshController.loadComplete();
    }
  }

  // 状态栏颜色
  Color _getHeadColor(int status, int receptorId) {
    String color = '#ffffff';
    // 待接收
    if (status == 0 && receptorId == 0) {
      color = '#FDF4F3';
    }
    // 待清点
    if (status == 0 && receptorId != 0) {
      color = '#FEFAF2';
    }
    // 已清点
    if (status == 10 && receptorId == 1) {
      color = '#F5F8FF';
    }
    return Utils.hexToColor(color);
  }

  // 状态栏状态文字转换
  String _getStatusTex(int status, int receptorId, Map status_text) {
    // 待接收
    if (status == 0 && receptorId == 0) {
      return '待接收';
    } else if (status == 10 && receptorId == 1) {
      return '已清点';
    }

    return status_text[status.toString()];
  }

  // 状态栏状态字体颜色
  Color _getStatusTextColor(int status, int receptorId) {
    String color = '#333333';
    // 待接收
    if (status == 0 && receptorId == 0) {
      color = '#F44745';
    }
    // 待清点
    if (status == 0 && receptorId != 0) {
      color = '#FF9132';
    }
    // 已清点
    if (status == 10 && receptorId == 1) {
      color = '#3F9DFF';
    }
    return Utils.hexToColor(color);
  }

  // 按钮颜色
  Color _getButtonColor(int status, int receptorId) {
    String color = '#dddddd';
    // 待接收
    if (status == 0 && receptorId == 0) {
      color = '#297BFF';
    }
    // 待清点
    if (status == 0 && receptorId != 0) {
      color = '#FF9131';
    }
    // 已清点
    if (status == 10 && receptorId == 1) {
      color = '#3F9DFF';
    }
    return Utils.hexToColor(color);
  }

  // 按钮文字转换
  String _getButtonText(int status, int receptorId) {
    // 待接收
    if (status == 0 && receptorId == 0) {
      return '接受任务';
    } else {
      return '清点物资';
    }
  }

  // 接受任务弹窗
  Future<void> _showTaskDialog(int id) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return DialogTask(id: id, showButton: true);
        });
  }

  _buildOrderNo(item) {
    var model = widget.model;

    switch (model) {
      case 'enter':
        return '入库单号：' + item['order_info']['order_no'];
      case 'storage':
        return '入库单号：' + item['order_info']['order_no'];
      case 'auction':
        return '拍卖单号：' + item['order_info']['out_code'];
      case 'destroy':
        return '销毁单号：' + item['order_info']['out_code'];
      case 'sample':
        return '取样单号：' + item['order_info']['out_code'];
      case 'return':
        return '退还单号：' + item['order_info']['out_code'];
      case 'donation':
        return '捐赠单号：' + item['order_info']['out_code'];
    }
  }

  _buildItemTitle(item) {
    var model = widget.model;

    switch (model) {
      case 'enter':
        return item['order_info']['case_name'];
      case 'storage':
        return item['order_info']['case_name'];
      case 'destroy':
        return item['order_info']['code'];
      case 'auction':
        return item['order_info']['code'];
      case 'destroy':
        return item['order_info']['code'];
      case 'sample':
        return item['order_info']['code'];
      case 'return':
        return item['order_info']['code'];
      case 'donation':
        return item['order_info']['code'];
    }
  }

  Widget _buildStatus(item) {
    return Text(
      _getStatusTex(item['order_info']['status'],
          item['order_info']['receptor_id'], item['status_text']),
      style: TextStyle(
          color: _getStatusTextColor(
              item['order_info']['status'], item['order_info']['receptor_id']),
          fontSize: 14),
    );
  }

  Widget _buildButton(item, index) {
    if ((widget.model == 'enter' || widget.model == 'storage') &&
        item['order_info']['status'] == 0) {
      return SizedBox(
          width: 160.w,
          height: 66.w,
          child: ElevatedButton(
            onPressed: () {
              // 接受任务
              if (item['order_info']['status'] == 0 &&
                  item['order_info']['receptor_id'] == 0) {
                _receiveTask(item['order_id'], index, item);
              }

              // 清点物资
              if (item['order_info']['status'] == 0 &&
                  item['order_info']['receptor_id'] != 0) {
                Navigator.pushNamed(context, "/task_enter_check",
                    arguments: {'id': item['order_id'], 'itemIndex': index});
              }
            },
            child: Text(
              _getButtonText(item['order_info']['status'],
                  item['order_info']['receptor_id']),
              style: TextStyle(color: Colors.white),
            ),
            style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 0),
                // color: Utils.hexToColor(item['btnColor'] ?? '#999999'),
                backgroundColor: _getButtonColor(item['order_info']['status'],
                    item['order_info']['receptor_id']),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(8.w)))),
          ));
    } else if (item['order_info']['business_group'] != '' &&
        item['order_info']['status'] == 3) {
      return SizedBox(
          width: 160.w,
          height: 66.w,
          child: ElevatedButton(
            onPressed: () {
              item['itemIndex'] = index;
              Navigator.pushNamed(context, "/task_out_library",
                  arguments: {'item': item});
            },
            child: Text(
              '分拣出库',
              style: TextStyle(color: Colors.white),
            ),
            style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 0),
                backgroundColor: Utils.hexToColor('#FF9232'),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(8.w)))),
          ));
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    // 无数据
    if (loadSuccess && list.length == 0) {
      return EmptyTips(
        refreshController: _refreshController,
        onRefresh: _onRefresh,
      );
    }

    return Container(
        width: 500.w,
        height: 270.w,
        color: Utils.hexToColor('#F5F6FA'),
        child: Refresh(
            refreshController: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
                itemCount: list.length,
                padding: EdgeInsets.only(bottom: 60.w),
                itemBuilder: (BuildContext context, int index) {
                  var item = list[index];

                  return Container(
                      width: 500.w,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20.w),
                      ),
                      margin: EdgeInsets.fromLTRB(25.w, 20.w, 25.w, 0.w),
                      child: InkWell(
                          onTap: () {
                            Navigator.pushNamed(context, '/task_detail',
                                arguments: {'item': item});
                          },
                          onTapDown: (details) {
                            FocusScope.of(context).requestFocus(FocusNode());
                          },
                          child: Column(children: <Widget>[
                            Container(
                              alignment: Alignment.center,
                              height: 90.w,
                              padding: EdgeInsets.fromLTRB(24.w, 0, 24.w, 0.w),
                              decoration: BoxDecoration(
                                color: _getHeadColor(
                                    item['order_info']['status'],
                                    item['order_info']['receptor_id']),
                                borderRadius: BorderRadius.vertical(
                                    top: Radius.circular(20.w)),
                              ),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      Image.asset('assets/rk.png', width: 40.w),
                                      Container(
                                        margin: EdgeInsets.only(left: 10.w),
                                        child: Text(
                                          _buildOrderNo(item),
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 14,
                                              height: 1),
                                        ),
                                      )
                                    ],
                                  ),
                                  _buildStatus(item)
                                ],
                              ),
                            ),
                            Container(
                                height: 180.w,
                                alignment: Alignment.topLeft,
                                padding:
                                    EdgeInsets.fromLTRB(24.w, 30.w, 24.w, 0.w),
                                child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: <Widget>[
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start, // 左对齐
                                        children: <Widget>[
                                          Text(_buildItemTitle(item),
                                              style: TextStyle(
                                                  color: Color(0xFF333333),
                                                  fontSize: 15,
                                                  fontWeight: FontWeight.bold,
                                                  height: 1)),
                                          Container(
                                            margin: EdgeInsets.only(top: 22.w),
                                            child: Text(
                                                '申请时间：' + item['create_time'],
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(top: 13.w),
                                            child: Text(
                                                '申请人：' +
                                                    item['order_info']
                                                        ['username'],
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                        ],
                                      ),
                                      _buildButton(item, index)
                                    ]))
                          ])));
                })));
  }
}
